#include <GL/glut.h>
#include <iostream>
#include <cstdlib>
#include "texturemanager.h"
#include "common.h"

TextureManager::TextureManager() {

}

TextureManager::~TextureManager() {

}

Texture* TextureManager::getTexture(std::string filename) {
	int texturefound = 0;
	if (filename.size() == 0) {
		ERROR("getTexture(): filename is empty!");
		return 0;
	}
	std::list<Texture*>::iterator it;
	LOG("number of textureList elements: " << m_textureList.size());
	
	//there are already some Textures
	if (m_textureList.size()>0) {
		LOG("TextureManager: m_textureList is NOT empty! searching for requested texture...");
		for (it=m_textureList.begin(); it!=m_textureList.end(); it++) {
	//		LOG("address: " << *it << " m_id: " << (*it)->m_id);

			//right Texture found!
			if (filename == (*it)->m_textureFilename) {
				LOG("TextureManager: requested texture found!");
				texturefound = 1;
				return *it;
			}
		}
		//that particular texture couldn't be found
		if (texturefound == 0) {
			LOG("TextureManager: Texture couldn't be found! Creating it..."); 
			//so we have to create it
			m_textureList.push_back(new Texture);
			//load the texture file
			m_textureList.back()->loadGLTextures(filename);
			//and return the pointer to the Texture
			return m_textureList.back();
		}
	}
	//if textureList is completely empty
	else {
		LOG("TextureManager: No Textures found at all! Creating it..."); 
		//we have to create a new texture
		m_textureList.push_back(new Texture);
		//load the texture file
		m_textureList.back()->loadGLTextures(filename);
		//and return the pointer to the Texture
		return m_textureList.back();
	}
	//we should never get here so we return 0
	return 0;
}

